<template>
  <div class="offlineMessage">
    <div class="info">
      <template v-if="notifyStatusStr == 1">
        {{$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.des1')}}
        <span @click="sendOfflineMessage">
          {{$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.des2')}}
        </span>
      </template>
      <template v-else-if="notifyStatusStr == 2">
        {{$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.des3')}}
      </template>
    </div>
    <el-dialog
      :append-to-body="true"
      :title="$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.title1')"
      :visible.sync="visible"
      width="420px"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        
        label-position="top"
        v-if="visible"
        @submit.native.prevent
      >
        <el-form-item :label="$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.label1')" prop="sendTypes">
          <el-checkbox-group v-model="ruleForm.sendTypes">
            <el-checkbox v-for="(v,i) in typeList" :key="i" :label="v">{{typeTextMaps[v]}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.label2')" prop="replyMessage">
          <el-input
            v-model="ruleForm.replyMessage"
            :placeholder="$t('common.placeholder.inputSomething', {data1:$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.label2')})"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="offlineMessage-warming">
        * {{$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.des4')}}
      </div>
      <div class="offlineMessage-warming">
        * {{$t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.des5')}}
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="confirm" :loading="pending"
          >{{$t('common.base.send')}}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
/** api */
import { offLineNotify,getNotifyMode } from '@src/api/ImApi.js';
/** vue */
import EventBus from '@src/util/eventBus';

import i18n from '@src/locales'

export default {
  name: 'offlineMessage',
  props: {
    msgList: {
      type: Array,
      default: () => [],
    },
    conversationId: {
      type: Number,
    },
    userDetail:{
      type:Object,
      default:()=>({})
    },
  },
  data() {
    return {
      visible: false,
      pending: false,
      ruleForm: {
        sendTypes: [],
        replyMessage: '',
      },
      rules: {
        sendTypes: [
          {
            type: 'array',
            required: true,
            message: i18n.t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.tips1'),
            trigger: 'change',
          },
        ],
        replyMessage: [
          { required: true, message: i18n.t('im.imChat.components.messageBox.chattingRecords.components.offlineMessage.tips2'), trigger: 'change' },
        ],
      },
      typeList:[],
      typeTextMaps:{
        'phone': i18n.t('common.base.sms'),
        'officialAccount':i18n.t('common.base.publicGroupOfWechat'),
        'email':i18n.t('common.base.email')
      },
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.getNotifyMode()
        this.ruleForm.sendTypes = [];
        if (this.lastMessage?.messageType == 'txt') {
          this.ruleForm.replyMessage = this.lastMessage.messageContent.msg;
        } else {
          this.ruleForm.replyMessage = '';
        }
      }
    },
  },
  computed: {
    lastMessage() {
      let message = this.msgList.findLast(v => v.sendType == '1');
      if (message?.messageType == 'txt') return message;
      return {};
    },
    notifyStatusStr(){
      return this.userDetail?.notifyStatusStr ?? 2
    }
  },
  methods: {
    sendOfflineMessage() {
      this.visible = true
      this.$track.clickStat(this.$track.formatParams('OFFLINE_NOTIFICATION'))
    },
    confirm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          try {
            const isNewMessage =
              this.ruleForm.replyMessage !==
              this.lastMessage?.messageContent?.msg;
            const params = {
              conversationId: this.conversationId,
              notifyMode: this.ruleForm.sendTypes,
              replyMessage: this.ruleForm.replyMessage,
              newMessage: isNewMessage,
            };
            this.pending = true;
            const { code, message, data } = await offLineNotify(params);
            if (code == 0) {
              this.$message.success(this.$t('common.base.sendSuccess'));
              this.visible = false;
              data?.map(item=>{
                EventBus.$emit('addMessageByKF', item);
              })
              EventBus.$emit('updateUserDetail', {...this.userDetail,notifyStatusStr:2});
            } else {
              this.$message.error(message);
            }
          } catch (err) {
            console.log(err);
          } finally {
            this.pending = false;
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async getNotifyMode(){
      try{
        const {code,data,message} = await getNotifyMode()
        if(code==0){
          this.typeList = data
        }else{
          this.$message.error(message)
          this.typeList = []
        }
      }catch(err){
        console.log(err)
      }
    },
  },
};
</script>

<style scoped lang="scss">
.offlineMessage {
  width: 100%;
  padding: 5px 10px;
  box-sizing: border-box;
  background-color: #ffffff;
  z-index: 999;
  .info {
    width: 100%;
    background-color: #fafafa;
    border-radius: 2px;
    padding: 4px 10px;
    span {
      color: $color-primary-light-6;
      cursor: pointer;
    }
  }
}
</style>
<style lang="scss">
.offlineMessage-warming {
  color: rgb(255, 167, 38);
  padding: 5px 10px;
}
</style>
